package gu.simplemq.redis;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.google.common.net.HostAndPort;

import gu.simplemq.BaseMessageQueueFactory;
import gu.simplemq.MQInstanceSupplier;
import gu.simplemq.pool.NamedMQPools;
import gu.simplemq.redis.JedisPoolLazy.PropName;

import static gu.simplemq.redis.JedisUtils.initAsRedisParameters;
import static gu.simplemq.utils.TypeConversionSupport.asProperties;
import static com.google.common.base.MoreObjects.firstNonNull;

/**
 * {@link gu.simplemq.IMessageQueueFactory}接口的redis实现类
 * @author guyadong
 *
 */
public final class MessageQueueFactoryImpl extends BaseMessageQueueFactory<JedisPoolLazy>{

	private HashMap<PropName, Object> props;
	private final RedisMQInstanceSupplier mqInstanceFactory;
	private final NamedMQPools<JedisPoolLazy> namedMQPools;
	MessageQueueFactoryImpl() {
		super(PropertiesHelper.RHELPER);
		this.mqInstanceFactory = RedisMQInstanceSupplier.MQ_INSTANCE_SUPPLIER;
		namedMQPools = JedisPoolLazys.NAMED_POOLS;
	}
	
	@Override
	protected NamedMQPools<JedisPoolLazy> getNamedMQPools() {
		return namedMQPools;
	}

	@Override
	protected MQInstanceSupplier<JedisPoolLazy> getMqInstanceFactory() {
		return mqInstanceFactory;
	}

	/**
	 * REDIS实现不支持单独指定 pub/sub(订阅发布) 连接参数，所以重写此方法以禁用此功能
	 */
	@SuppressWarnings("rawtypes")
	@Override
	protected void doInit(Map properties){
		mqConnParams = properties;
		props = initAsRedisParameters(firstNonNull(properties, Collections.<String, Object>emptyMap()));
		pool = namedMQPools.defineDefaultPool(asProperties(properties));
	}
	@Override
	protected HostAndPort doGetHostAndPort() {
		return JedisUtils.getHostAndPort(props);
	}
}
